package com.yoso.core.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil;
import com.google.common.collect.Lists;

import java.lang.reflect.Field;
import java.util.List;

/**
 * 比较工具
 * @author shizejin
 * @date 2023/11/28 10:08
 */
public class CompareUtil {
    public static final String DIFF_TEMPLATE = "%s：由【%s】变化为【%s】";

    /**
     * 比较字段值的差异, 并转化为描述信息
     * @param left 参照对象
     * @param right 比较对象
     * @param ignoreFieldList 忽略的字段
     * @return {@link List }<{@link String }>
     * @author shizejin
     * @date 2023/09/15 14:18
     */
    public static <T> List<String> parseCompareValue2Content(T left, T right, List<String> ignoreFieldList) {
        List<String> content = Lists.newArrayList();
        for (Field leftField : ReflectUtil.getFields(left.getClass())) {
            String fieldName = leftField.getName();
            if (CollUtil.contains(ignoreFieldList, fieldName)) {
                continue;
            }
            Object leftValue = ReflectUtil.getFieldValue(left, fieldName);
            Object rightValue = ReflectUtil.getFieldValue(right, fieldName);

            String leftStrValue = String.valueOf(leftValue);
            String rightStrValue = String.valueOf(rightValue);
            if (leftStrValue.equals(rightStrValue)) {
                continue;
            }
            content.add(String.format(DIFF_TEMPLATE, fieldName, leftStrValue, rightStrValue));
        }
        return content;
    }
}
